var util = require('../../utils/util.js');  
var dateTimePicker = require('../../utils/dateTimePicker.js');
var isBooking = false;
var bookTime = "";
var cityId = 0;
var areaId = 0;
var streetId = 0;
var addressStr = '';
var concatName = '';
var concatTel = '';
var citys = [];
var areas = [];
var streets = [];
var addressList = [];
var concatId = 0;
var weightCode = "";
var addressItemsList = [];
const app = getApp();
Page({
  data: {
    btn_submit:"一键下单",
    btn_color:"#00e600",
    startTime: "08:00:00",
    endTime: "18:00",
    selDate:"",
    isHidden: true,
    isHiddenAddress:true,
    serviceItems: [
    { name: 'onTimeService', value: '尽快服务', checked: 'true' },
    { name: 'timingService', value: '定时服务' }
    ] ,
    addressItems: [
      { name: 'defaultAddress', value: '默认地址', checked: 'true' },
      { name: 'changeAddress', value: '选择地址' }
    ] ,
    weightItems: null,
    priceItems:null,
    weightIndx : 0,
    date: '2018-10-01',
    time: '12:00',
    dateTimeArray: null,
    dateTime: null,
    dateTimeArray1: null,
    dateTime1: null,
    startYear: 2000,
    endYear: 2050,
    chooseSize: false,
    animationData: {},
    hiddenmodalput: true,
    addressList: [],
    citys: citys,
    areas: areas,
    streets: streets,
    addressMenuIsShow:true,
    dateMenuIsShow:true,
    value: [0, 0, 0],
    areaInfo: "",
    userType:0,
    addressInfo:"",
    addressIndex:0
  },
  submit:function(e){
    console.log("开始回收。");

    var orderJson = '{"isBooking":false,"bookTime":null}';
    this.setData({
      btn_color:"gray"
    })
    //判断是否预约
    if (isBooking){
      orderJson = '{"weightCode":"' + weightCode + '","concatId":' + concatId+ ',"isBooking":true,"bookTime":"' + bookTime + '"}';
    }else{
      orderJson = '{"weightCode":"' + weightCode + '","concatId":' + concatId + ',"isBooking":false,"bookTime":null}';
    }
    console.log("orderJson值为：" + orderJson)
    console.log("请求token=" + getApp().globalData.token)
    wx.request({/**通过code获取openid**/
      url:   getApp().globalData.server_support + "/collect-scrap/saveUserOrder",
      data: orderJson,
      header: {
        'token': getApp().globalData.token,
        'content-type': 'application/json;charset=utf-8'
      },
      method: 'POST',
      success: function (res) {
        console.log(res);
        if (res.data.success) {
          wx.switchTab({
            url: '../../pages/orderview/orderview'
          }); 
        } else {
          console.log("提交订单失败");
        }
      }
    });
    console.log("结束回收。");
  }, radioChange: function (e) {
    console.log(e.detail.value);
    if ("timingService" == e.detail.value) {
      isBooking = true;
      this.setData({
        isHidden: false
      })
    } else {
      isBooking = false;
      this.setData({
        isHidden: true
      })
    }
  },
  /**
   * 监听时间picker选择器
   */
  listenerStartTimePickerSelected: function (e) {
    console.log(e);
    //调用setData()重新绘制
    this.setData({
      startTime: e.detail.value,
    });
  },
  /**
   * 监听时间picker选择器
   */
  listenerEndTimePickerSelected: function (e) {
    console.log(e);
    //调用setData()重新绘制
    this.setData({
      endTime: e.detail.value,
    });
  },
  /**
   * 监听日期picker选择器
   */
  listenerDatePickerSelected: function (e) {
    console.log(e);
    this.setData({
      selDate: e.detail.value
    })
  },
  onLoad: function () {
    this.getOpenId();
    // 调用函数时，传入new Date()参数，返回值是日期和时间  
    var simpleDate = util.simpleDate(new Date());
    console.log(simpleDate);
    // 再通过setData更改Page()里面的data，动态更新页面的数据  
    this.setData({
      selDate: simpleDate
    });
    // 获取完整的年月日 时分秒，以及默认显示的数组
    var obj = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
    var obj1 = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
    // 精确到分的处理，将数组的秒去掉
    var lastArray = obj1.dateTimeArray.pop();
    var lastTime = obj1.dateTime.pop();

    this.dictList('weight-range');
    this.dictList('price');
    this.setData({
      dateTime: obj.dateTime,
      dateTimeArray: obj.dateTimeArray,
      dateTimeArray1: obj1.dateTimeArray,
      dateTime1: obj1.dateTime
    });
    bookTime = obj.dateTimeArray[0][obj.dateTime[0]] + "-" + obj.dateTimeArray[1][obj.dateTime[1]] + "-" + obj.dateTimeArray[2][obj.dateTime[2]] + " " + obj.dateTimeArray[3][obj.dateTime[3]] + ":" + obj.dateTimeArray[4][obj.dateTime[4]] + ":" + obj.dateTimeArray[5][obj.dateTime[5]];
  },
  parameterTap: function (e) {//e是获取e.currentTarget.dataset.id所以是必备的，跟前端的data-id获取的方式差不多
    var that = this
    var this_checked = e.currentTarget.dataset.code
    console.log(this_checked)
    weightCode = this_checked
    var parameterList = this.data.weightItems//获取Json数组
    for (var i = 0; i < parameterList.length; i++) {
      if (parameterList[i].code == this_checked) {
        parameterList[i].checked = true;//当前点击的位置为true即选中
      }
      else {
        parameterList[i].checked = false;//其他的位置为false
      }
    }
    that.setData({
      weightItems: parameterList
    })
},
  onShow: function () {
    wx.setNavigationBarTitle({
      title: '三轮兄弟'
    })
    this.setData({
      userType: app.globalData.userType 
    })
    this.getOpenId()
    //this.modeLogin()
  },
  changeDate(e) {
    this.setData({ date: e.detail.value });
  },
  changeTime(e) {
    this.setData({ time: e.detail.value });
  },
  changeDateTime(e) {
    this.setData({ dateTime: e.detail.value });
  },
  changeDateTime1(e) {
    this.setData({ dateTime1: e.detail.value });
  },
  changeDateTimeColumn(e) {
    var arr = this.data.dateTime, dateArr = this.data.dateTimeArray;
    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
    this.setData({
      dateTimeArray: dateArr,
      dateTime: arr
    });
    console.log("选择时间如下");
    bookTime = dateArr[0][arr[0]] + "-" + dateArr[1][arr[1]] + "-" + dateArr[2][arr[2]] + " " + dateArr[3][arr[3]] + ":" + dateArr[4][arr[4]] + ":" + dateArr[5][arr[5]];
    console.log(bookTime);
  },
  addressChange:function(e){
    console.log(e.data)
  },
  choseAddress: function (e) { //点击筛选事件
    console.log(e.detail.value);
    if ("changeAddress" == e.detail.value){
      
      // 用that取代this，防止不必要的情况发生
      var that = this;
      that.getOpenId();
      // 创建一个动画实例
      var animation = wx.createAnimation({
        // 动画持续时间
        duration: 500,
        // 定义动画效果，当前是匀速
        timingFunction: 'linear'
      })
      // 将该变量赋值给当前动画
      that.animation = animation
      // 先在y轴偏移，然后用step()完成一个动画
      animation.translateY(200).step()
      // 用setData改变当前动画
      that.setData({
        // 通过export()方法导出数据
        animationData: animation.export(),
        // 改变view里面的Wx：if
        chooseSize: true
      })
      // 设置setTimeout来改变y轴偏移量，实现有感觉的滑动
      setTimeout(function () {
        animation.translateY(0).step()
        that.setData({
          animationData: animation.export()
        })
      }, 200)
    }else{
      var that = this;
      var animation = wx.createAnimation({
        duration: 1000,
        timingFunction: 'linear'
      })
      that.animation = animation
      animation.translateY(200).step()
      that.setData({
        animationData: animation.export()

      })
      setTimeout(function () {
        animation.translateY(0).step()
        that.setData({
          animationData: animation.export(),
          chooseSize: false
        })
      }, 200)
    } 
  },
  addNewAddress:function(){
    this.setData({
      hiddenmodalput: !this.data.hiddenmodalput
    }) 
    var data = this.data;
    wx.request({/**通过code获取openid**/
      url:  getApp().globalData.server_support + "/collect-scrap/queryDistrict",
      method: 'POST',
      success: function (res) {
        console.log("地址请求返回所有信息");
        console.log(res.data);
        console.log(this)
        if (res.data.success) {
          console.log("地址列表信息");
          console.log(res.data.data);
          addressList = res.data.data;;
          citys = addressList;
          areas = addressList[0].dataLists;
          streets = addressList[0].dataLists[0].dataLists;
        } else {
          console.log("获取不到地址信息")
        }
      }
    })
  },
  //取消按钮  
  cancel: function () {
    this.setData({
      hiddenmodalput: true
    });
  },
  //确认  
  confirm: function () {
    var that = this;
    that.setData({
      hiddenmodalput: true
    })
    console.log("开始填写地址。");
    var addJson = '{ "province": "0", "contactName": "' + concatName + '", "city": "' + cityId + '", "region": "' + areaId + '", "street": "' + streetId + '", "address": "' + addressStr + '", "tel": "' + concatTel + '" }';
    console.log(addJson);
    wx.request({/**通过code获取openid**/
      url:   getApp().globalData.server_support + "/collect-scrap/saveUserAddr",
      data: addJson,
      header: {
        'token': getApp().globalData.token,
        'content-type': 'application/json;charset=utf-8'
      },
      method: 'POST',
      success: function (res) {
        console.log(res);
        if (res.data.success) {
          that.getOpenId();
        } else {
        }
      }
    })
    console.log("结束填写地址。");
  },
  addressInput: function (e) {
    addressStr = e.detail.value
  },
  concatNameInput: function (e) {
    concatName = e.detail.value
  },
  concatPhoneInput: function (e) {
    concatTel = e.detail.value
  }
  ,
  selectDistrict: function (e) {
    this.setData({
      dateMenuIsShow: !this.data.dateMenuIsShow
    }) 
    var that = this
    console.log("城市地址")
    console.log(citys)
    console.log("区地址")
    console.log(areas)
    console.log("街道地址")
    console.log(streets)
    that.setData({
      addressList: addressList,
      citys: citys,
      areas: areas,
      streets: streets
    })
    // 如果已经显示，不在执行显示动画
    if (that.data.addressMenuIsShow) {
      return
    }
    // 执行显示动画
    that.startAddressAnimation(true)
  },
  // 执行动画
  startAddressAnimation: function (isShow) {
    console.log(isShow);
    console.log(citys);
    var that = this
    that.setData({
      addressMenuIsShow: isShow
    })
  },
  // 点击地区选择取消按钮
  cityCancel: function (e) {
   // this.startAddressAnimation(false)
    this.setData({
      dateMenuIsShow: true
    });
  },
  // 点击地区选择确定按钮
  citySure: function (e) {
    this.setData({
      dateMenuIsShow: true
    });
    var data = this.data
    this.startAddressAnimation(false)
    // 将选择的城市信息显示到输入框
    cityId = data.citys[data.value[0]].districtId;
    areaId = data.areas[data.value[1]].districtId;
    streetId = data.streets[data.value[2]].districtId
    var areaInfo = data.citys[data.value[0]].districtName + "." + data.areas[data.value[1]].districtName
      + "." + data.streets[data.value[2]].districtName
    this.setData({
      areaInfo: areaInfo,
    })
  },
  // 点击蒙版时取消组件的显示
  hideCitySelected: function (e) {
    console.log(e)
    this.startAddressAnimation(false)
  },
  // 处理省市县联动逻辑
  cityChange: function (e) {
    console.log(e)
    var value = e.detail.value
    var citys = this.data.citys
    var areas = this.data.areas
    var streets = this.data.streets
    var cityNum = value[0]
    var areaNum = value[1]
    var streetNum = value[2]
    console.log("cityNum=" + cityNum + ":" + value[0] + ":" + this.data.value[0])
    console.log("areaNum=" + areaNum + ":" + value[1] + ":" + this.data.value[1])
    console.log("streetNum=" + streetNum + ":" + value[2] + ":" + this.data.value[2])
    // 如果省份选择项和之前不一样，表示滑动了省份，此时市默认是省的第一组数据，
    if (this.data.value[0] != cityNum) {
      var data = this.data;
      this.setData({
        value: [cityNum, 0, 0],
        areas: data.addressList[cityNum].dataLists,
        streets: data.addressList[cityNum].dataLists[0].dataLists
      })
    } else if (this.data.value[1] != areaNum) {
      // 滑动选择了第二项数据，即市，此时区显示省市对应的第一组数据
      var data = this.data;
      console.log("选择了区地址")
      console.log(data.addressList[cityNum].dataLists[areaNum])
      this.setData({
        value: [cityNum, areaNum, 0],
        streets: data.addressList[cityNum].dataLists[areaNum].dataLists == null ? [] : data.addressList[cityNum].dataLists[areaNum].dataLists,
      })
    } else {
      // 滑动选择了区
      this.setData({
        value: [cityNum, areaNum, streetNum]
      })
    }
    console.log(this.data)
  },
  selAddress: function (e) {
    console.log("选择地址");
    console.log(e.detail.value);
    concatId = e.detail.value;
    var addressInfo = '';
    console.log(addressItemsList)
    var addressIndex = 0;
    for (var index in addressItemsList) {
      console.log(addressItemsList[index].id)
      if (addressItemsList[index].id == concatId) {
        console.log(addressItemsList[index].address)
        addressInfo = addressItemsList[index].address;
        addressIndex = index;
      }
    }
    this.setData({
      addressMenuIsShow: "visible",
      addressInfo: addressInfo,
      addressIndex: addressIndex
    })
    var that = this;
    var animation = wx.createAnimation({
      duration: 1000,
      timingFunction: 'linear'
    })
    that.animation = animation
    animation.translateY(200).step()
    that.setData({
      animationData: animation.export()

    })
    setTimeout(function () {
      animation.translateY(0).step()
      that.setData({
        animationData: animation.export(),
        chooseSize: false
      })
    }, 200)
  },
  parameterTap: function (e) {//e是获取e.currentTarget.dataset.id所以是必备的，跟前端的data-id获取的方式差不多
    var that = this
    var this_checked = e.currentTarget.dataset.code
    console.log(this_checked)
    var index = 0;
    var parameterList = this.data.weightItems//获取Json数组
    for (var i = 0; i < parameterList.length; i++) {
      if (parameterList[i].dictItem == this_checked) {
        index = i;//当前点击的位置为true即选中
      }
    }
    that.setData({
      weightItems: parameterList,
      weightIndx:index
    })
    
  },
  //下拉刷新
  onPullDownRefresh: function () {
    wx.showNavigationBarLoading() //在标题栏中显示加载

    //模拟加载
    setTimeout(function () {
      // complete
      wx.hideNavigationBarLoading() //完成停止加载
      wx.stopPullDownRefresh() //停止下拉刷新
    }, 1500);
  },
  dictList: function (groupId){
    var that = this
    wx.request({/**通过code获取openid**/
      url:  getApp().globalData.server_support + "/collect-scrap/queryDictList",
      data: groupId,
      header: {
        'content-type': 'application/json;charset=utf-8'
      },
      method: 'POST',
      success: function (res) {
        console.log("请求重量字典")
        console.log(res.data.data);
        weightCode = res.data.data[0].dictItem
        if (res.data.success) {
          if ("weight-range" == groupId){
            that.setData({ weightItems:res.data.data})
          }
          if ("price" == groupId) {
            that.setData({ priceItems: res.data.data })
          }
        } else {
           
        }
      }
    });
  },
  chooseAddress2: function () { //点击筛选事件
    console.log("选择地址");
    // 用that取代this，防止不必要的情况发生
    var that = this;
    // 创建一个动画实例
    var animation = wx.createAnimation({
      // 动画持续时间
      duration: 500,
      // 定义动画效果，当前是匀速
      timingFunction: 'linear'
    })
    // 将该变量赋值给当前动画
    that.animation = animation
    // 先在y轴偏移，然后用step()完成一个动画
    animation.translateY(200).step()
    // 用setData改变当前动画
    that.setData({
      // 通过export()方法导出数据
      animationData: animation.export(),
      // 改变view里面的Wx：if
      chooseSize: true
    })
    // 设置setTimeout来改变y轴偏移量，实现有感觉的滑动
    setTimeout(function () {
      animation.translateY(0).step()
      that.setData({
        animationData: animation.export()
      })
    }, 200)
  },
  getOpenId:function(){
    var that = this;
    wx.login({
      success: function (res) {
        wx.request({/**通过code获取openid**/
          url: getApp().globalData.server_support + "/collect-scrap/queryOpenId",
          data: res.code,
          method: 'POST',
          success: function (res) {
            console.log("订单查询openid")
            console.log(res)
            console.log(res.data.data.openid)
            that.queryUserAddress2(res.data.data.openid)
          }
        })
      }
    })
  },
  queryUserAddress2: function (openid) {
    var that = this;
    wx.request({/**通过code获取openid**/
      url:   getApp().globalData.server_support + "/collect-scrap/queryUserAddrByUserName",
      data: openid,
      header: {
        'content-type': 'application/json;charset=utf-8'
      },
      method: 'POST',
      success: function (res) {
        console.log("获取地址成功")
        console.log(res.data.data);
        if (res.data.data != null && res.data.data.length > 0){
          addressItemsList = res.data.data;
          concatId = res.data.data[0].id;
          that.setData({
            addressItemsList: res.data.data,
            addressInfo: res.data.data[0].address
          });
        }
      }
    });
  },
  modeLogin:function(){
    wx.login({
      success: function (res) {
        wx.request({
          //获取openid接口  
          url: 'https://api.weixin.qq.com/sns/jscode2session',
          data: {
            appid: "wxc3633354f1bcb343",
            secret: "a729a89ea5428b6ee89b9a7e025164ef",
            js_code: res.code,
            grant_type: 'authorization_code'
          },
          method: 'GET',
          success: function (res) {
            console.log(res.data)
            var OPEN_ID = res.data.openid;//获取到的openid 
            getApp().globalData.openid = res.data.openid;
            wx.request({/**通过code获取openid**/
              url: getApp().globalData.server_support + "/collect-scrap/register",
              data: '{"userName":"' + OPEN_ID + '","userPassword":"","userType":"0"}',
              method: 'POST',
              success: function (res) {
                console.log(res);
                if (res.data.success) {
                  console.log("登陆成功");
                  getApp().globalData.token = res.data.data.token;
                } else {
                  wx.showLoading({
                    title: '登录失败'
                  });
                  setTimeout(function () {
                    wx.hideLoading();
                  }, 500)
                }
              }
            })
          }
        })
      }
    })  
  }
});